
import re

from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users.models import User

"""
序列化器的功能：
１、验证数据
２、数据入库
３、将模型转换为字典

"""

class RegisterUserSerializer(serializers.ModelSerializer):
    # write_only 在当前情况下，　只用于　反序列化的数据验证操作，
    # True,为确保在更新或创建实例时可以使用该字段，但在序列化表示时不包括该字段。
    # 序列化器实现　模型转字典
    #短信验证码
    sms_code=serializers.CharField(required=True,max_length=6,min_length=6,write_only=True)
    #确认密码
    password2=serializers.CharField(required=True,allow_null= False,allow_blank= False,write_only=True)
    #是否同意协议
    allow=serializers.CharField(required=True,allow_blank=False,allow_null=False,write_only=True)

    #只是在 登陆注册 之后返回,只是获取数据
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['id','token','username','mobile','password','sms_code','allow','password2']

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }




    """
    1、数据类型的验证
    2、数据选项的验证
    3、单个字段的验证
    4、多个字段的验证

    """
    # 单个字段
    def validate_mobile(self,value):

        # ①手机号的规则
        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    # ②是否同意协议
    def validate_allow(self,value):

        if value != 'True':
            raise serializers.ValidationError('您未同意协议')

        return value

    # 多个字段
    def validate(self, attrs):
        #1、密码和确认密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('密码不一致')

        #比较手机验证码
        #获取用户提交的验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')

        # 获取redis中的验证码
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s'%mobile)

        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        #比对
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    #当父类的需求不能满足我们开发的时候  就要重写方法
    def create(self, validated_data):
        # 删除多余字段
        del validated_data['sms_code']
        del validated_data['allow']
        del validated_data['password2']
        #自己实现数据保存
        # user = User.objects.create(**validated_data)
        user = super().create(validated_data)

        #修改密码
        user.set_password(validated_data.get('password'))
        user.save()  #模型的save

        #在这里生成token
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user






class UserCenterInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','email','mobile','email_active']





class EmailUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['email']
        extra_kwargs = {
            'email':{'required':True}
        }




from .models import Address
class AddressesCreateSerializer(serializers.ModelSerializer):

    # 序列化的时候使用
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    # 反序列化的时候使用
    province_id = serializers.IntegerField(label='省ID',required=True)
    city_id = serializers.IntegerField(label='市ID',required=True)
    district_id = serializers.IntegerField(label='区ID',required=True)

    mobile = serializers.RegexField(label='手机号',regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user','is_deleted','create_time','update_time')

    def create(self, validated_data):

        user = self.context['request'].user

        validated_data['user']=user

        return super().create(validated_data)


class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    province_id = serializers.IntegerField(label='省ID',required=True)
    city_id = serializers.IntegerField(label='市ID',required=True)
    district_id = serializers.IntegerField(label='区ID',required=True)

    mobile = serializers.RegexField(label='手机号',regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user','is_deleted','create_time','update_time')

    def create(self, validated_data):
        # Address模型类中有user属性，将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title')


class UserHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品id',required=True,min_value=1)

    def validate_sku_id(self,value):

        # sku_id判断商品id是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('添加的商品不存在')

        return value

    def create(self, validated_data):

        # 将数据保存在redis中
        #①链接redis
        redis_conn = get_redis_connection('history')
        #②获取sku_id,user_id
        sku_id = validated_data.get('sku_id')
        user = self.context['request'].user
        #添加之前 先删除可能存在的sku_id
        redis_conn.lrem('history_%s' % user.id,0,sku_id)
        #③保存到列表中
        redis_conn.lpush('history_%s'%user.id,sku_id)
        #④只保留前五个
        redis_conn.Itrim('history_s'%user.id,0,4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id','name','price','default_image_url','comments')


















